package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import com.bit101.components.PushButton;
	import flash.utils.Timer;
	
	[SWF(width=500,height=300)]
	public class AnimatorTimeFrame extends Sprite 
	{
		private var rect:Sprite;
		private var timer:Timer;
		
		public function AnimatorTimeFrame():void 
		{
			if (stage) 
				init();
			else 
				addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			rect = new RectContainer(0, 0, 200, 200);                        
			addChild(rect);        
			
			// 设置计时器，每50毫秒出发一次
			timer = new Timer(50);
			
			var enterFrameBtn:PushButton = new PushButton(this, 0, 250, "Event.ENTER_FRAME");
			enterFrameBtn.name = "ENTER_FRAME";
			enterFrameBtn.addEventListener(MouseEvent.CLICK, onClickHander);
			
			var timerBtn:PushButton = new PushButton(this, 120, 250, "Event.Timer");
			timerBtn.name = "TIMER";
			timerBtn.addEventListener(MouseEvent.CLICK, onClickHander);            
			
		}
		
		private function onClickHander(e:MouseEvent):void 
		{
			var name:String = e.target.name as String;
			if (name == "ENTER_FRAME")
			{
				timer.stop();
				rect.addEventListener(Event.ENTER_FRAME, animateFrame);
			}
			else if (name == "TIMER")
			{
				rect.removeEventListener(Event.ENTER_FRAME, animateFrame);                    
				timer.addEventListener(TimerEvent.TIMER, animateTimer);    
				timer.start();
			}
			
		}
		
		private function animateFrame(e:Event):void 
		{
			rect.x += 5;
			if (rect.x >= stage.stageWidth)
			{
				rect.x = 0;
			}
		}
		
		private function animateTimer(e:TimerEvent):void 
		{
			rect.x += 1;
			if (rect.x >= stage.stageWidth)
			{
				rect.x = 0;
			}
			
			e.updateAfterEvent();
		}        
	}
	
}